﻿using CefSharp;
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;

namespace CefDemo.cef
{
    public class ResourceSchemeHandler : ResourceHandler
    {
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri = new Uri(request.Url);
            var file = uri.Authority + uri.AbsolutePath;
            var ass = Assembly.GetExecutingAssembly();
            var resourcePath = ass.GetName().Name + "." + file.Replace("/", ".");

            Task.Run(() =>
            {
                using (callback)
                {
                    var stream = ass.GetManifestResourceStream(resourcePath);
                    var mimeType = "text/html";
                    switch (Path.GetExtension(file))
                    {
                        case ".html":
                            mimeType = "text/html";
                            break;
                        case ".js":
                            mimeType = "text/javascript";
                            break;
                        case ".css":
                            mimeType = "text/css";
                            break;
                        case ".png":
                            mimeType = "image/png";
                            break;
                        case ".jpg":
                        case ".jpeg":
                            mimeType = "image/jpeg";
                            break;
                        case ".gif":
                            mimeType = "image/gif";
                            break;
                        case ".appcache":
                        case ".manifest":
                            mimeType = "text/cache-manifest";
                            break;
                        default:
                            mimeType = "application/octet-stream";
                            break;
                    }
                    if (stream == null)
                    {
                        callback.Cancel();
                    }
                    else
                    {
                        //Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                        stream.Position = 0;
                        //Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                        ResponseLength = stream.Length;
                        MimeType = mimeType;
                        StatusCode = (int)HttpStatusCode.OK;
                        Stream = stream;
                        callback.Continue();
                    }
                }
            });
            return CefReturnValue.ContinueAsync;
        }
    }
}
